<template>
    <div id = "container"></div>
    <van-button round
                type="success"
                size="large"
                id="signButton"
                color="green"
                @click="onClick()"
                v-show="showButton">{{buttonText}}
    </van-button>

</template>

<script setup >
import {useRoute} from "vue-router";
import {onMounted, ref, watchEffect} from "vue";
import myAxios from "../../plugins/myAxios.ts";
import axios from 'axios';
import {showConfirmDialog, showDialog, showSuccessToast, showToast} from "vant";
import {getCurrentUser} from "../services/user.ts";
import apiAxios from "../../plugins/apiAxios.ts";

const route = useRoute();
const userList = ref([]);
const loading = ref(false);
const signLocate = ref('');
const signStationInfo = ref('');
const currentUser = ref('');
const isShow = true;
const lngDeptLocation = ref('');
const latDeptLocation = ref('');
const signGpsLocation= ref('');
const detailLocation = ref('');
onMounted(async () => {
    currentUser.value = await getCurrentUser();
    signLocate.value = await signLocation();
    signStationInfo.value = await signStation();
    getPosition(signStationInfo.value);
    await getDetailLocationByGps("120.3532,30.3104");
})

/**
 * 默认匹配用户
 */
const doDefault = async () =>{
    loading.value = true;
    await delay(1000);
    const userListData = await myAxios.get('/user/recommend',{
        params:{
            pageSize: 8,
            pageNum: 1,
        },
    })
        .then(function (response) {
            // console.log("/user/search/tags success",response);
            showToast("请求成功")
            return response.data?.data?.records;
        })
        .catch(function (error){
            // console.log("/user/search/tags error",error);
            showToast("请求失败")
        })
    if (userList){
        userListData.forEach(user => {
            if (user.tags){
                user.tags = JSON.parse(user.tags);
            }
        })
        userList.value = userListData;
    }
    loading.value = false;
}

/**
 * 精确匹配用户
 */
const doMatch = async () =>{
    loading.value = true;
    await delay(1000);
    const num = 10;
    const userListData = await myAxios.get('/user/match',{
        params:{
            num,
        },
    })
        .then(function (response) {
            showToast("请求成功")
            return response.data?.data;
        })
        .catch(function (error){
            showToast("请求失败")
        })
    if (userList){
        userListData.forEach(user => {
            if (user.tags){
                user.tags = JSON.parse(user.tags);
            }
        })
        userList.value = userListData;
    }
    loading.value = false;
}
const handleSwitchChange = (value) =>{
    if (value){
        doMatch();
    }else {
        doDefault();
    }
}
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

function getPosition(){
    if (navigator.geolocation) {
        // 走到这里说明，浏览器支持geolocation，参数里有两个回调函数，一个是定位成功后的处理操作，一个是定位失败后的处理操作，另外一个参数没有研究过
        navigator.geolocation.getCurrentPosition(onSuccess, onError);
    } else {
        // 否则浏览器不支持geolocation
        alert('您的浏览器不支持地理位置定位！');
    }

}

async function onSuccess(position) {
  // 返回用户位置
  // 经度
  var longitude = position.coords.longitude;
  // 纬度
  var latitude = position.coords.latitude;
  signGpsLocation.value = longitude.toString() + "," + latitude.toString();
  detailLocation.value = await getDetailLocationByGps(signGpsLocation.value);
  var ggPoint = new BMap.Point(longitude, latitude);

  var ggDeptPoint = new BMap.Point(lngDeptLocation.value, latDeptLocation.value);
  console.log("gps的经纬度", ggPoint);
  // alert('您的当前地址的经纬度：经度' + longitude + '，纬度' + latitude);
  var bm = new BMap.Map("container");
  bm.centerAndZoom(ggPoint, 15);
  bm.addControl(new BMap.NavigationControl());

  //坐标转换完之后的回调函数
  var convertor = new BMap.Convertor();
  var pointArr = [];
  pointArr.push(ggPoint);
  pointArr.push(ggDeptPoint);
  //转换经纬度,然后在地图上标点
  convertor.translate(pointArr, 1, 5, function (data) {
    translateCallback(data, bm)
  })
}
function onError(error) {
    switch (error.code) {
        case 1:
            alert("位置服务被拒绝！");
            break;
        case 2:
            alert("暂时获取不到位置信息！");
            break;
        case 3:
            alert("获取信息超时！");
            break;
        case 4:
            alert("未知错误！");
            break;
    }
    // 这里后面可以写你的后续操作了，下面的经纬度是天安门的具体位置
    // handleData(longitude, latitude);
}
function translateCallback (data,bm){
    console.log(data.points)
    if(data.status === 0) {
        //目前你的位置
        var marker = new BMap.Marker(data.points[0]);
        console.log("百度地图接口的位置",marker)
        bm.setCenter(data.points[0]);
        var labelgg = new BMap.Label("你当前的位置",{offset:new BMap.Size(20,-10)});
        marker.setLabel(labelgg);
        bm.addOverlay(marker);
        // var ggPoint2 = new BMap.Point(120.16078006899,30.33135949886);
        var ggPoint2 = new BMap.Point(data.points[1].lng,data.points[1].lat);
        var circle = new BMap.Circle(ggPoint2, signLocate.value.localRange, { // 考勤地点范围,这个位置也需要转换
            fillColor: "blue", // 圆形颜色
            strokeWeight: 2,
            fillOpacity: 0.2,
            strokeOpacity: 0.2
        });
        bm.addOverlay(circle);
        var distance = bm.getDistance(data.points[0], ggPoint2).toFixed(2);
        if (distance > 100000){
            //针对不同的判断情况设置签到颜色的变化
            document.getElementById('signButton').style.backgroundColor = 'gray'
            showToast("超出考勤范围,无法签到")
        }else{
            document.getElementById('signButton').style.backgroundColor = 'green'
        }
    }
}

/**
 *  得到这个按钮的颜色,判断签到的情况
 */

const onClick = async () => {
  let flag = 1;
  let flagChiDao = 0;
  let flagZaoTui = 0;
  const color = document.getElementById('signButton').style.backgroundColor;
  //判断位置在范围内
  if (color === 'green'){
     //签到
    if (signStationInfo.value === "signIn"){
      if (signLocate.value.signInTimeSFM > signLocate.value.nowTimeSFM){
        showToast("签到成功");
      }else {
        flagChiDao = 1;
        showToast("签到成功但已经迟到了,下次记得早点来");
      }
      //签退
    }else if (signStationInfo.value === "signOut"){
      if (signLocate.value.signOutTimeSFM > signLocate.value.nowTimeSFM) {
          console.log(signLocate.value.signOutTimeSFM);
          console.log(signLocate.value.nowTimeSFM);
          await showConfirmDialog({
              title: '早退啦',
              message:
                  '确定要早退吗',
          })
              .then(() => {
                  showToast("签退成功,早退了");
                  flagZaoTui = 1;
              })
              .catch(() => {
                  flag = 0;
                  showToast("再坚持一下就可以签退了");
              });
      }else {
          showToast("签退成功");
      }
      //已经签到过了
    }else {
      showToast("今天已经签到过了,请不要重复签到")
    }
    if (flag === 1){
      await myAxios.post('/userSignState/sign',{
        gpsLocation:signGpsLocation.value,
        detailLocation:detailLocation.value.data,
        signState:signStationInfo.value,
        lateSign:flagChiDao,
        earlySign:flagZaoTui
      })
        //同时更新用户得到状态
        signStationInfo.value = await signStation();
    }
  }else{
    showToast("定位失败.你不在签到范围内")
  }

}


const signLocation = async () => {
  const signLocationRes =  await myAxios.get('/userSignState/signLocation',{});
    const parts = signLocationRes.data.data.deptSignGpsLocation.split(",");
    //分割经纬度
    lngDeptLocation.value = parts[0]; // 经度部分
    latDeptLocation.value = parts[1]; // 纬度部分
  return signLocationRes.data.data;
}


const showButton = ref(true);
const buttonText = ref('签到');

const signStation = async () => {
  const signStationRes =  await myAxios.get('/userSignState/signStation',{});
  if (signStationRes.data.data === "signIn"){
    // 修改按钮文本内容
      if (currentUser.value.data.signInAlarm === 1){
          showToast("请签到")
      }

    buttonText.value = '签到';
  }else if (signStationRes.data.data === "signOut"){
      if (currentUser.value.data.signOutAlarm === 1){
          showToast("请签退")
      }
    buttonText.value = '签退';
  }else{
    showButton.value = false;
    if (currentUser.value === null){
      showToast("没登陆")
      buttonText.value = '请登录';
    }else{
        showDialog({
            title: '',
            message: '今天已经签到完成了，明天再来吧',
        }).then(() => {
            // on close
        });
    }
  }
  return signStationRes.data.data;
}
const getDetailLocationByGps = async (gpsLocationParam) =>{
  const signStationRes =  await myAxios.get('/userSignState/getDetailLocation',{
    params:{
      gpsLocation: gpsLocationParam,
    }});
  return signStationRes.data;
}
</script>

<style scoped>
#container{
    height: 70vh;
}
#signButton{
    width: 15vh; /* 按钮宽度 */
    height: 15vh; /* 按钮高度 */
    border-radius: 50%; /* 将按钮设置为圆形 */
    text-align: center; /* 文字居中 */
    line-height: 50px; /* 垂直居中 */
    top: 10px; /* 距离顶部的距离 */
    left: 50%; /* 水平居中 */
    transform: translateX(-50%); /* 水平居中 */
}

</style>